/* eslint-disable */
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { dataFetch, dataType } from '@pier88health/p8h-common'
import i18n from '@I18N'
import DBConfig from '@CONFIG/DBConfig'
import { FILE_TYPE_ENUM, GENDER_TYPE } from '@CONSTANTS/common'
import { MESSAGE_TYPE } from '@CONSTANTS/chat'
import Scenes from '@NAVIGATION/scenes'
import { DURATION_TEXT_MAP } from '@CONSTANTS/meditation'
import {
  CLIENT_TYPE_MAP,
  WEB_NAV_HEIGHT,
  HIDE_NAV_PAGE,
  LANGUAGE,
} from '@CONSTANTS/app'
import Navigate from '@NAVIGATION/navigateManager'
import { REPORT_TRENT_TEXT } from '@CONSTANTS/planManagement'
import Images from '@ASSET/Images';
import { TagNameMap, TagTypeEnum } from '@CONSTANTS/tag'
import { Analytic_Type } from '@CONSTANTS/analytic'

const NAVIGATOR_HEIGHT = 44
const TAB_BAR_HEIGHT = 50
const TAB_EVENT_MAP = {
  [Scenes.homePage]: 'num_tab_main',
  [Scenes.expertPage]: 'num_tab_pain',
  [Scenes.myPage]: 'num_tab_my',
  [Scenes.dataCenter]: 'num_tab_dataCenter',
}

export function getClientType() {
  const platfrom = Taro.getEnv();
  return CLIENT_TYPE_MAP[platfrom]
}

export function getPlatform() {
  const platfrom = Taro.getEnv();
  return {
    isRN: platfrom === Taro.ENV_TYPE.RN, //React Native 环境
    isWeb: platfrom === Taro.ENV_TYPE.WEB, //网页、H5环境
    isWX: platfrom === Taro.ENV_TYPE.WEAPP, //微信小程序环境
    isSwan: platfrom === Taro.ENV_TYPE.SWAN, //百度小程序环境
    isAlipay: platfrom === Taro.ENV_TYPE.ALIPAY, // 支付宝小程序环境
    isTT: platfrom === Taro.ENV_TYPE.TT // 字节跳动小程序环境
  };
}

export const networkInfo = {
  isConnected: true,
  networkType: 'wifi'
}

export const isWxBrowser = () => {
  if (!getPlatform().isWeb) return false
  const ua = navigator.userAgent.toLowerCase()
  const isWXWork = ua.match(/wxwork/i) == 'wxwork'
  return !isWXWork && ua.indexOf('micromessenger') > -1
}

export const isMiniprogramBrowser = () => {
  if(!getPlatform().isWeb) return false
  //https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html#%E7%9B%B8%E5%85%B3%E6%8E%A5%E5%8F%A3-5
  const ua = navigator.userAgent.toLowerCase()
  return ua.includes('miniprogram')
}

export function isMobile() {
  const isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)
  return getPlatform().isWeb && isMobile
}

export const isWhiteList = () => {
  if (!isWxBrowser) return true
  const origin = 'care.p88health.com'
  let currentHref = location.href
  return currentHref.includes(origin) && !currentHref.includes('devcare') && !currentHref.includes('stcare')
}
const showNetworkTips = () => {
  Taro.showToast({
    title: '当前无网络，请重新联网',
    icon: 'none',
    duration: 3000
  })
}

Taro.getNetworkType({
  success: res => {
    networkInfo.isConnected = res.networkType !== 'none'
    networkInfo.networkType = res.networkType
    if (res.networkType === 'none') {
      showNetworkTips()
    }
  }
})

Taro.onNetworkStatusChange(function (res) {
  networkInfo.isConnected = res.isConnected
  networkInfo.networkType = res.networkType

  if (!res.isConnected) {
    showNetworkTips()
  }
})

let _systemInfo = null
let _isXPhoneArea = null
export const getSystemInfo = () => {
  const info = Taro.getSystemInfoSync()
  if (isPc()) {
    info.windowWidth = 375
  }
  if (_systemInfo === null) {
    _systemInfo = info
  }

  return info
}

export const isAndroid = () => {
  const _systemInfo2 = getSystemInfo()
  return _systemInfo2.platform === 'android'
}


export const isIOSWeb = () => {
  if(!getPlatform().isWeb) return false
  return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //iosH5终端
}

export const isIOS = () => {
  const info = Taro.getSystemInfoSync()
  if (getPlatform().isWeb) {
    return isIOSWeb()
  }
  return info.platform === 'ios'
}

/** 判断是否是 IphoneX、iPhone 11 系列 */
export const isIphoneSafeArea = () => {
  if (_isXPhoneArea === null) {
    const { model = '', brand = '', statusBarHeight = 0 } = getSystemInfo()
    _isXPhoneArea = (statusBarHeight === 44 || statusBarHeight === 48) && (model.includes('iPhone') || brand.includes('Apple') || brand.includes('iPhone'))
  }
  return _isXPhoneArea
}

export function h5PageModalTips() {

  Taro.showModal({
    showCancel: false,
    title: '提示',
    cancelColor: '#595959',
    content: '本网站为“彼爱医疗”的Web版本，其功能只适用于智能触屏手机使用。',
  })
}

export const formatUnitTime = time => time?.toString()
  .padStart(2, '0')

export const getTimeRemaining = (endTime, startTime) => {
  const countTime = (endTime - (startTime || Date.now())) / 1000
  const fullTime = {
    h: formatUnitTime(Math.floor(countTime / 3600)),
    m: formatUnitTime(Math.floor(countTime / 60) % 60),
    s: formatUnitTime(Math.floor(countTime % 60)),
    totalTime: countTime
  }
  return fullTime
}

export const countDown = (endTime, getFullTime, startTime) => {
  let timer = null
  timer = setInterval(
    () => {
      const fullTime = getTimeRemaining(endTime, startTime)
      if (fullTime.totalTime > 0) {
        getFullTime?.(Object.assign({}, fullTime, { isDone: false }))
      } else {
        timer && clearInterval(timer)
        getFullTime?.(Object.assign({}, fullTime, { isDone: true }))
      }
    },
    1000
  );

  return timer
}

/**
 * 返回屏幕可用高度
 * @param {*} showTabBar
 */
export function getWindowHeight(showTabBar = false) {
  const info = getSystemInfo()
  const { windowHeight, statusBarHeight } = info
  const tabBarHeight = showTabBar ? TAB_BAR_HEIGHT : 0

  if (process.env.TARO_ENV === 'rn') {
    return windowHeight - statusBarHeight - NAVIGATOR_HEIGHT - tabBarHeight
  }
  if (process.env.TARO_ENV === 'h5') {   
    return windowHeight - tabBarHeight
  }

  return windowHeight
}

/**
 * 返回屏幕宽度
 */
export function getWindowWidth() {
  const info = getSystemInfo()
  const { windowWidth } = info
  return windowWidth
}

export const timestampFormatDate = inputTime => {
  let date = new Date(parseInt(inputTime) * 1000);
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  let h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  let minute = date.getMinutes();
  let second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}

export const formatData = (nextData, prevData = {}) => {
  const res = nextData.reduce((prev, next) => {
    const temp = { ...prev }
    const time = next.DateBucket
    const formatTime = time.split('-')
    const month = formatTime[1]
    const day = formatTime[2]
    if (!temp[time]) {
      temp[time] = {
        Logs: [next],
        Month: month,
        Day: day,
      }
    } else {
      temp[time].Logs?.push(next)
    }
    return temp
  }, prevData)
  return res
}

export const replaceOther = (list, otherText) => {
  let replaceList = list
  if (otherText) {
    replaceList = Array.isArray(list) && list.map(item => (item.en === 'Other' ? {
      en: otherText,
      zh: otherText
    } : item))
  }
  return replaceList
}

export function pxTransform(px) {
  return getPlatform().isWeb ? Taro.pxTransform(px, 375) : `${px * getWindowWidth() / 375}px`
}

export function getEqualPx(px) {
  const windowWidth = getWindowWidth()
  return parseInt(windowWidth * px / 375, 10)
}

export function getWebRealPx(px) {
  const { isWeb } = getPlatform()
  const { windowWidth } = getSystemInfo()
  if (!isWeb) {
    return px
  }
  const pathname = getPathname()
  const tabBarHeight = [Scenes.homePage].includes(pathname) ? 50 : 0
  const webNavHeight = HIDE_NAV_PAGE.includes(pathname) ? 0 : WEB_NAV_HEIGHT
  return windowWidth / 375 * px + webNavHeight + tabBarHeight
}

export function getClassName(name) {
  return getPlatform().isWeb ? `${name}-web` : name
}

export function isMobileBrowser() {
  return getPlatform().isWeb && !isWxBrowser()
}

export const getImageExtension = (type, isOnlyWeb = true) => {
  if (!type) return null
  if (isOnlyWeb && !getPlatform().isWeb) return null

  if (type.indexOf('png') > -1) return 'png'
  return 'jpg'
}

export function convertParamsToString(params) {
  if (!params || !dataType.isObject(params)) return '';
  let paramsStr = '?'
  Object.entries(params)
    .map(([key, value]) => {
      if (key && value) {
        let currentValue = dataType.isObject(value) ? JSON.stringify(value) : value
        paramsStr += `${key}=${currentValue}&`;
      }
    })
  return paramsStr.slice(0, -1);
}

export const getPatientInfo = (name, gender, birthdate, language = 'zh') => (`${name?.[language]}  ${GENDER_TYPE[gender]} ${dataFetch.getAgeByTime(birthdate)}`)
let lastPage = ''
export const handleClickTab = (path, params = {}) => {
  const eventId = TAB_EVENT_MAP[path];
  if (path !== lastPage) {
    Taro.eventCenter.trigger('onClickTab', path, lastPage)
  }
  eventId && Taro.tracker.trackEvent(eventId, params)
  lastPage = path
}

export function checkIsAndroid() {
  const u = navigator.userAgent
  return u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
}

export const stdConfig = {};
stdConfig.isToken = false;

export const getMessageContent = message => {
  if (!dataType.isObject(message)) return ''
  const { MessageType, SurveyTitle } = message || {}
  switch (MessageType) {
    case MESSAGE_TYPE.Audio:
      return `[${i18n.message.audio_type()}]`
    case MESSAGE_TYPE.DoctorAdvice:
      return `[${i18n.message.doctor_advice()}]`
    case MESSAGE_TYPE.Rating:
      return `[${i18n.comment.finish_comment()}]`
    case MESSAGE_TYPE.SurveyRequest:
      return SurveyTitle?.[LANGUAGE.ZH] || `[${i18n.message.questionnaire()}]`
    case MESSAGE_TYPE.Prescription:
      return '[电子处方]'
    case MESSAGE_TYPE.FeedItem:
    case MESSAGE_TYPE.CareCourse:
    case MESSAGE_TYPE.PainManagement:
      return `[${i18n.common.link()}]`
    case MESSAGE_TYPE.ConsultationCouponGift:
      return `[图文咨询卡]`
    case MESSAGE_TYPE.MedRecord:
        return `[${i18n.patient.elect_med_record()}]`
    default:
      const { image, text, PatientContent } = message
      if (image) {
        return `[${i18n.common.picture()}]`
      }
      return PatientContent || text
  }
}

export function addZero4Date(m) {
  if (m < 10) return `0${m}`
  return `${m}`
}

export function renderVideoTime(seconds = 0) {
  const sec = seconds % 60
  const min = parseInt(seconds / 60, 10) % 60
  const hour = parseInt(seconds / 60 / 60, 10)
  if (hour) {
    return `${addZero4Date(hour)}:${addZero4Date(min)}:${addZero4Date(sec)}`
  }
  return `${addZero4Date(min)}:${addZero4Date(sec)}`
}

export const getRealRouterParams = params => {
  const { q } = params || {}
  let realParams = {}
  if (q) {
    realParams = dataFetch.getQueryParams(decodeURIComponent(q))
  } else {
    realParams = params
  }
  return realParams
}

export const getRouterValue = key => {
  const value = getCurrentInstance().router.params?.[key]
  if (!getPlatform().isWX) return value
  const q = getCurrentInstance().router.params?.q
  if (q) {
    const keyObj = dataFetch.getQueryParams(decodeURIComponent(q))
    return keyObj?.[key]
  }
  return value
}

export const setWebTitle = title => {
  const { isWeb } = getPlatform()
  if (!isWeb) return
  title && (document.title = title)
  const pageTitle = document.getElementById('pageTitle')
  pageTitle && (pageTitle.innerHTML = title)
  title && Taro.setNavigationBarTitle({ title })
}

export const setNavigationBarTitle = title => {
  if (!title) return
  const { isWeb } = getPlatform()
  const titleStr = decodeURIComponent(title || '')
  if (isWeb) return setWebTitle(titleStr)
  Taro.setNavigationBarTitle({ title: titleStr })
}

export const showToast = (msg, duration = 1000) => {
  return Taro.showToast({
    title: msg.message || msg.message || msg,
    duration: duration,
    icon: 'none'
  })
}

export const convertPx = px => {
  const { isRN } = getPlatform()
  return isRN ? px : `${px}px`
}

export function mapListForSyncData({ list, itemKey, itemInsideKey, changeKey, params }) {
  return (
    Array.isArray(list) && list.map(item => {
      const curKey = itemInsideKey ? item?.[itemKey]?.[itemInsideKey] : item?.[itemKey]
      return (curKey === changeKey ? { ...item, ...params } : item)
    })
  )
}

export const getTagIds = tags => (Array.isArray(tags) ? tags.map(item => (item.TagId)) : [])

export const formatPictureFiles = ({ data, dateBucket }) => {
  if (!Array.isArray(data) || data.length === 0) return []
  const imgList = data.map(source => {
    const fullPath = `${DBConfig.staticConsultation}${dateBucket}/${source}`
    return {
      path: fullPath,
      isReUpload: true,
      fileName: source,
      dateBucket
    }
  })
  return imgList
}

export const getPathname = () => {
  if (!getPlatform().isWeb) return ''
  return window.location.pathname
}

export const getLocationSearch = () => {
  if (!getPlatform().isWeb) return ''
  const temp = window.location.hash.split('?')
  const search = temp[1]?.slice(1)
  return dataFetch.getQueryParams(search)
}

export function renderCount(data) {
  const count = data?.toString() || ''
  if (count === '') {
    return ''
  }
  const len = count.length
  if (len <= 3) {
    return count
  }
  return `${(Math.floor(count / 100) / 10).toFixed(1)}k`
}

export const openPage = (routeKey, routerData) => {
  const { isWX, isWeb } = getPlatform()
  if (routeKey==='url') return Navigate.webView({src: encodeURIComponent(routerData?.url)})
  if (routeKey !== 'wmpRoute') return Navigate[routeKey]?.({ ...routerData })
  const path = routerData?.path?.replace(/&amp;/g, '&')
  const h5path = routerData?.h5path
  const { wxAppId, envVersion = 'release' } = dataFetch.getQueryParams(`${path}`)
  if (isWeb && h5path) {
    top.location = h5path
    return
  }
  if (isWX && wxAppId) {
    Taro.navigateToMiniProgram({
      appId: wxAppId,
      path,
      envVersion
    })
  }
}

const isPc = () => {
  if (!getPlatform().isWeb) return false
  return !isMobile()
}

export const getShareMeditationTitle = (durationTime, totalTime) => {
  const totalMin = Math.ceil(totalTime / 60)
  const curMin = Math.ceil(durationTime / 60)
  let curIndex
  if (curMin <= 1) {
    curIndex = 1
  } else if (curMin <= 3) {
    curIndex = 3
  } else if (curMin <= 5) {
    curIndex = 5
  } else if (curMin <= 10) {
    curIndex = 10
  } else if (curMin <= 15) {
    curIndex = 15
  } else if (curMin <= 20) {
    curIndex = 20
  } else if (curMin <= 25) {
    curIndex = 25
  } else {
    curIndex = 30
  }
  return `我已冥想${curMin}分钟，累计${totalMin}分钟。${DURATION_TEXT_MAP[`time_${curIndex}`]}`
}

export const getCoverImageUrl = name => `${DBConfig.staticMeditationImageUrl}${name}?x-oss-process=image/resize,w_160`
export const getBackgroundAudioUrl = name => `${DBConfig.staticMeditationUrl}${name}`

export const formatSecond = second => {
  const min = Math.floor(second / 60)
  const sec = second % 60
  return `${min > 9 ? '' : '0'}${min}:${sec > 9 ? '' : '0'}${sec}`
}

export const isShowVideo = () => {
  return !getPlatform().isWX
}

export const getNavBar = (hideNavBar=false) => {
  const { statusBarHeight = 20, windowWidth, windowHeight } = Taro.getSystemInfoSync()

  if (!getPlatform().isWX) {
    return {
      windowHeight,
      navBarHeight: hideNavBar?0:50,
      menuHeight: 36,
      statusBarHeight: 0,
      paddingRight: 0
    }
  }
  const {
    top = statusBarHeight + 4, right = windowWidth - 10, bottom = statusBarHeight + 32 + 8, height = 32, width = 87
  } = Taro.getMenuButtonBoundingClientRect() || {}

  return {
    windowHeight,
    menuHeight: height,
    navBarHeight: statusBarHeight + (top - statusBarHeight) * 2 + height,
    statusBarHeight,
    paddingRight: windowWidth - right + width
  }
}

export const searchRouterKey = path => {
  const item = Object.entries(Scenes)
    .find(scene => scene[1] === path)
  return item?.[0] || 'homePage'
}

export const getTrendConfig = (value, type) => {
  const { up, down, icon, title, desc, chartDesc } = REPORT_TRENT_TEXT[type] || REPORT_TRENT_TEXT.LifeImpactTrend
  let trendText = '持平'
  let trendIcon = Images.home.icon_feed_back_same
  if (value > 0) {
    trendText = up
    trendIcon = Images.home.icon_feed_back_up
  } else if (value < 0) {
    trendText = down
    trendIcon = Images.home.icon_feed_back_down
  }
  return {
    trendIcon,
    trendText,
    icon,
    title,
    desc,
    chartDesc
  }
}

export const isImage = (type) => {
  if (!type) return false
  return [
    FILE_TYPE_ENUM.jpg, FILE_TYPE_ENUM.png, FILE_TYPE_ENUM.gif,
    FILE_TYPE_ENUM.bmp, FILE_TYPE_ENUM.webp,
    FILE_TYPE_ENUM.jpeg].includes(type)
}

export const getCustomTagTitle = (title, type) => {
  switch (type) {
    case TagTypeEnum.Survey:
      const currTitle = TagNameMap.survey[title] || `${title || ''}${i18n.tag.tagSurvey()}`
      return { title: currTitle }
    default:
      return { title: '' }
  }
}

export const showModal = ({
  title = '', content, confirm = ()=> {}, cancel = () => {
  }, eventData, confirmText = '确定', cancelText = '取消'
}) => {
  Taro.showModal({
    title: title,
    content: content,
    confirmText: confirmText,
    cancelText: cancelText,
    mask: true,
    confirmColor: '#47C690',
    cancelColor: '#595959',
    success: res => {
      const isConfirm = res.confirm
      if(!isConfirm && !res.cancel) return
      if (isConfirm) {
        confirm?.()
      } else if(res.cancel){
        cancel?.()
      }
      const curEventData = Object.assign({}, eventData, { BtnType: isConfirm ? confirmText : cancelText })
      Taro.tracker.trackEvent(Analytic_Type.tap_dialog.eventId, curEventData)
    }
  })
}

export const getPageHeightStyle = () => {
  const { isWeb } = getPlatform()
  return { height: convertPx(getWindowHeight(isWeb)) }
}

export const getFileInfo = (file) => {
  const { size, path, originalFileObj } = file
  let fileName = ''
  if (getPlatform().isWeb) {
    fileName = originalFileObj.name
  } else {
    fileName = path.slice(path.lastIndexOf('/') + 1)
  }
  const shortFileName = fileName.slice(0, fileName.lastIndexOf('.'))

  return {
    fileName,
    shortFileName,
    ext: fileName.slice(fileName.lastIndexOf('.') + 1),
    size,
  }
}

export function encryptionMobile(str){
  if(!str || str.length !== 11) return str
  let pat=/(\d{3})\d*(\d{4})/;
  return str.replace(pat,'$1****$2');
}

export const setTaroPageHeight = (height = '100%') => {
  const refs = document.querySelectorAll('.taro_page')
  refs.forEach(item => {
    item.style.height = height
  })
}

function delay(delayTime = 25){
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, delayTime)
  })
}

export function delayQuerySelector(
  selectorStr,
  delayTime = 500
) {
  return new Promise(resolve => {
    const selector = Taro.createSelectorQuery()
    delay(delayTime).then(() => {
      selector
        .select(selectorStr)
        .boundingClientRect()
        .exec((res) => {
          resolve(res)
        })
    })
  })
}
